package com.ruoyi.login;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.ruoyi.appletsutil.AppletsLoginUtils;
import com.ruoyi.appletsutil.ResultCode;
import com.ruoyi.appletsutil.UnAuthorizedException;
import com.ruoyi.common.annotation.UnAuth;
import com.ruoyi.common.constant.Rediskey;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.bean.AccessTokenResult;
import com.ruoyi.common.utils.bean.UserInfoResult;
import com.ruoyi.common.utils.bean.WeChatAppletLoginResponse;
import com.ruoyi.common.utils.bean.WechatSetting;
import com.ruoyi.member.domain.UmsMember;
import com.ruoyi.member.service.IUmsMemberService;
import com.ruoyi.member.service.LoginService;
import com.ruoyi.member.service.RegisterServiceApi;
import com.ruoyi.member.service.WeChatAppletLoginService;
import com.ruoyi.member.vo.*;
import com.ruoyi.setting.bean.WechatPaySet;
import com.ruoyi.setting.service.ILsPaySettingService;
import com.ruoyi.util.AES;
import com.ruoyi.util.CommonConstant;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 登录控制器
 *
 * @author SK
 * @since 2018/6/13
 */
@RestController
@Slf4j
@Api(description = "登录接口")
public class LoginController {

    /**
     * 注入微信小程序登录服务
     */
    @Autowired
    private WeChatAppletLoginService weChatAppletLoginService;

    /**
     * 注入redis服务
     */
    @Autowired
    private RedisCache redisService;
    /**
     * 注入注册聚合服务
     */
    @Autowired
    private RegisterServiceApi registerServiceApi;

    /**
     * jwt密钥
     */
    @Value("${token.secret}")
    private String jwtSecretKey;

    /**
     * 注入登录处理service
     */
    @Resource(name = "loginService")
    private LoginService loginService;


    /**
     * 注入随机数生成器
     */
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    /**
     * 注入支付设置服务
     */
    @Autowired
    private ILsPaySettingService paySetService;
    @Autowired
    private IUmsMemberService memberService;

    @GetMapping("/getJsapiTicket")
    @UnAuth
    @ResponseBody
    @ApiOperation(value = "会员登录", notes = "会员登录（不需要认证）")
    @ApiResponses({
            @ApiResponse(code = 200, message = "result: -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误  token:放登录成功后的token", response = Map.class)
    })
    public AjaxResult getJsapiTicket(@RequestParam(value = "storeId", required = false,defaultValue = "0")  long storeId, String url) {
        //获取微信登录设置
        WechatPaySet wechatAppletPaySet = paySetService.queryPaySet(storeId).getWechatPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
        // 获取微信分享access_token
        String access_token = WechatUtils.getAccessTokenForShare(wechatSetting);
        if (StringUtils.isEmpty(access_token)) {
            log.error("getWechatSignature fail due to access_token is null");
            return null;
        }
        // 获取微信分享jsapi_ticket
        String jsapi_ticket = WechatUtils.getJsapiTicketForShare(access_token);
        if (StringUtils.isEmpty(jsapi_ticket)) {
            log.error("getWechatSignature fail due to jsapi_ticket is null");
            return null;
        }
        // 获取随机字符串
        String noncestr = WechatUtils.getRandomString();
        // 获取时间戳
        String timestamp = WechatUtils.getTimeStamp();
        // 对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1&key2=value2…）拼接成字符串
        String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
        // 对拼接成的字符串进行SHA1加密
        String signature = SHA1Utils.encode(str);
        return AjaxResult.success(WechatResponse.buildCommunityBuyWechatResponse(wechatSetting.getAppId(), timestamp, noncestr, signature));
    }
    /**
     * 会员登录
     *
     * @param loginParams 登录参数
     * @return -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误
     */
    @PostMapping("/loginByPassword")
    @UnAuth
    @ResponseBody
    @ApiOperation(value = "会员登录", notes = "会员登录（不需要认证）")
    @ApiResponses({
            @ApiResponse(code = 200, message = "result: -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误  token:放登录成功后的token", response = Map.class)
    })
    public AjaxResult loginByPassword(@RequestBody LoginParams loginParams, HttpServletRequest request) {
        // 登录结果
        return loginService.login(loginParams);
    }

    /**
     * 会员手机验证码登录注册
     *
     * @param loginParams 登录参数
     * @return -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误
     */
    @PostMapping("/loginByCode")
    @UnAuth
    @ResponseBody
    @ApiOperation(value = "会员登录", notes = "会员登录（不需要认证）")
    @ApiResponses({
            @ApiResponse(code = 200, message = "result: -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误  token:放登录成功后的token", response = Map.class)
    })
    public AjaxResult loginByCode(@RequestBody LoginParams loginParams, HttpServletRequest request) {
        final StringBuilder sb = new StringBuilder();
        log.info("loginByCode :checkAppletOAuthParams code=" + loginParams.getCode());
        Map<String, Object> res = new HashMap<>();
        UmsMember member = memberService.queryCustomerByName(loginParams.getMobile(),loginParams.getStoreId());
        String originCode = redisService.getValue(String.format("%s_%s", CommonConstant.APPLET_REGISTER_CODE_KEY, loginParams.getMobile()));
        if (StringUtils.isEmpty(loginParams.getCode())) {
            log.error("loginByCode fail due to code is error...");
            return AjaxResult.error("loginByCode fail due to code is error...");
        }
        if (StringUtils.isEmpty(loginParams.getMobile())) {
            log.error("loginByCode fail due to mobile  is empty...");
            return AjaxResult.error("loginByCode fail due to mobile  is empty...");
        }
        if (!originCode.equals(loginParams.getCode())) {
            log.error("loginByCode fail due to code is error...");
            return AjaxResult.error("loginByCode fail due to code is error...");
        }
        if (member != null) {
            res.put("member", member);
        } else {
            member = new UmsMember();
            member.setSource("3");
            member.setUsername(loginParams.getMobile());
            member.setMobile(loginParams.getMobile());
            member.setPassword("123456");
            member.setStoreId(loginParams.getStoreId());
            member.setRelename("魔金" + RandomMathLetter.randomString(4));
            member.setConsumptionAmount(BigDecimal.ZERO);
            member.setRecommondCode(loginParams.getRecommondCode());
            memberService.insertUmsMember(member);
            //向线程池提交任务
            UmsMember finalMember = member;
            ThreadTask.getInstance().addTask(() -> {
                registerServiceApi.registerCoupon(finalMember.getId());
            });
            res.put("member", member);
        }
        sb.append(Jwts.builder().setSubject(member.getUsername())
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(SignatureAlgorithm.HS256, jwtSecretKey)
                .setIssuedAt(new Date())
                .claim("userName", member.getUsername())
                .claim("nickName", member.getNickname())
                .claim("releName", member.getRelename())
                .claim("id", member.getId())
                .setExpiration(Date.from(Instant.now().plus(1, ChronoUnit.HOURS))) // 有效期1小时
                .compact());

        redisService.putToRedis(String.format(Rediskey.TOKEN, sb.toString()), JSON.toJSONString(member),100, TimeUnit.DAYS);
        res.put("access_token", sb.toString());
        res.put("refresh_token", sb.toString());
        return AjaxResult.success(res);
    }

    /**
     * 会员登录
     *
     * @param loginParams 登录参数
     * @return -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误
     */
    @PostMapping("/logout")
    @UnAuth
    @ResponseBody
    @ApiOperation(value = "会员登录", notes = "会员登录（不需要认证）")
    @ApiResponses({
            @ApiResponse(code = 200, message = "result: -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误  token:放登录成功后的token", response = Map.class)
    })
    public AjaxResult logout(@RequestBody LoginParams loginParams, HttpServletRequest request) {
        redisService.deleteObject(String.format(Rediskey.TOKEN,getToken(request)));

        return AjaxResult.success();
    }

    /**
     * 公众号通过code登录
     * @param 。开发者需要在开发者服务器后台调用 api，使用 code 换取 openid 和 session_key 等信息
     * @return 登录信息
     */
    @UnAuth
    @ResponseBody
    @RequestMapping("/loginByWeiXinCode")
    @ApiOperation(value = "公众号获取登录信息", notes = "公众号获取登录信息（不需要认证）", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "code", value = "用户登录凭证"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "登录信息", response = AppletLoginInfo.class)
    })
    public AjaxResult loginByWeiXinCode(String code,@RequestParam(value = "recommondCode", required = false) String recommondCode, @RequestParam(value = "storeId", required = false,defaultValue = "0")  long storeId, HttpServletRequest request) {
        final StringBuilder sb = new StringBuilder();
        log.info("getLoginInfo :checkAppletOAuthParams code=" + code);
        Map<String, Object> res = new HashMap<>();
        WechatPaySet wechatAppletPaySet = paySetService.queryPaySet(storeId).getWechatPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
        if (!wechatSetting.checkAppletOAuthParams()) {
            log.error("getLoginInfo fail:checkAppletOAuthParams fail");
            return AjaxResult.error("getLoginInfo fail:checkAppletOAuthParams fail");
        }
        WeChatAppletLoginResponse weChatAppletLoginResponse = WechatUtils.getLoginInfo(code, wechatSetting);
        if (Objects.isNull(weChatAppletLoginResponse)) {
            log.error("getLoginInfo fail: getLoginInfo fail");
            return AjaxResult.error("getLoginInfo fail: getLoginInfo fail");
        }

        log.info("getOpenId : openid==" + weChatAppletLoginResponse.getOpenid());
        AppletLoginRedisParamResponse appletLoginRedisParamResponse = new AppletLoginRedisParamResponse();
        UmsMember member = memberService.queryCustomerByh5OpenId(weChatAppletLoginResponse.getOpenid(),appletLoginRedisParamResponse.getStoreId());
        if (member != null) {
            appletLoginRedisParamResponse.setCustomerId(member.getId());
            appletLoginRedisParamResponse.setToken(sb.toString());
            res.put("member", member);
        } else {
            member = new UmsMember();
            UserInfoResult userInfo = WechatUtils.getUserInfo(weChatAppletLoginResponse.getAccess_token(), weChatAppletLoginResponse.getOpenid());
            if (userInfo != null) {
                member.setNickname(userInfo.getNickname());
                member.setImage(userInfo.getHeadimgurl());
                member.setGender(userInfo.getSex());
            }
            member.setSource("3");
            member.setMobile(RandomMathLetter.randomInt(11));
            member.setPassword("123456");
            member.setStoreId(storeId);
            member.setRelename("魔金" + RandomMathLetter.randomString(4));
            member.setH5OpenId(weChatAppletLoginResponse.getOpenid());
            member.setConsumptionAmount(BigDecimal.ZERO);
            //设置自己的推荐码
            member.setRecommondCode(recommondCode);
            memberService.insertUmsMember(member);
            //向线程池提交任务
            UmsMember finalMember = member;
            ThreadTask.getInstance().addTask(() -> {
                registerServiceApi.registerCoupon(finalMember.getId());
            });

            res.put("member", member);
        }
        sb.append(Jwts.builder().setSubject(member.getUsername())
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(SignatureAlgorithm.HS256, jwtSecretKey)
                .setIssuedAt(new Date())
                .claim("userName", member.getUsername())
                .claim("nickName", member.getNickname())
                .claim("releName", member.getRelename())
                .claim("id", member.getId())
                .setExpiration(Date.from(Instant.now().plus(1, ChronoUnit.HOURS))) // 有效期1小时
                .compact());
        appletLoginRedisParamResponse.setToken(sb.toString());
        redisService.putToRedis(String.format(Rediskey.TOKEN, sb.toString()), JSON.toJSONString(member),100, TimeUnit.DAYS);
        res.put("access_token", sb.toString());
        res.put("refresh_token", sb.toString());
        return AjaxResult.success(res);
    }



    /**
     * 检测token
     */
    @RequestMapping("/verifyToken")
    @UnAuth
    @ResponseBody
    public AjaxResult verifyToken(String token, HttpServletRequest request) {

        return AjaxResult.success();
    }

    /**
     * 小程序登录
     *
     * @param 。开发者需要在开发者服务器后台调用 api，使用 code 换取 openid 和 session_key 等信息
     * @return 登录信息
     */
    @UnAuth
    @ResponseBody
    @RequestMapping("/mpWechatLogin")
    @ApiOperation(value = "小程序获取登录信息", notes = "小程序获取登录信息（不需要认证）", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "code", value = "用户登录凭证"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "登录信息", response = AppletLoginInfo.class)
    })
    public AjaxResult mpWechatLogin(@RequestBody AppletLoginRedisParamResponse appletLoginRedisParamResponse, HttpServletRequest request) {
        final StringBuilder sb = new StringBuilder();

        Map<String, Object> res = new HashMap<>();

        WechatPaySet wechatAppletPaySet = paySetService.queryPaySet(appletLoginRedisParamResponse.getStoreId()).getWechatAppletPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
        if (!wechatSetting.checkAppletOAuthParams()) {
            log.error("getLoginInfo fail:checkAppletOAuthParams fail");
            return AjaxResult.error("getLoginInfo fail:checkAppletOAuthParams fail");
        }
        WeChatAppletLoginResponse weChatAppletLoginResponse = WeChatAppletUtils.getLoginInfo(appletLoginRedisParamResponse.getCode(), wechatSetting);
        if (Objects.isNull(weChatAppletLoginResponse)) {
            log.error("getLoginInfo fail: getLoginInfo fail");
            return AjaxResult.error("getLoginInfo fail: getLoginInfo fail");
        }
        appletLoginRedisParamResponse.setSessionKey(weChatAppletLoginResponse.getSession_key());
        appletLoginRedisParamResponse.setOpenId(weChatAppletLoginResponse.getOpenid());
        UmsMember member = memberService.queryCustomerByappletOpenId(weChatAppletLoginResponse.getOpenid(),appletLoginRedisParamResponse.getStoreId());
        if (member != null) {
            appletLoginRedisParamResponse.setCustomerId(member.getId());
            appletLoginRedisParamResponse.setToken(sb.toString());
            res.put("member", member);
        } else {
            member = new UmsMember();
            UserInfo userInfo = appletLoginRedisParamResponse.getUserInfo();
            log.error("getLoginInfo fail: getLoginInfo fail:{}", userInfo);
            if (userInfo != null) {
                member.setNickname(userInfo.getNickName());
                member.setImage(userInfo.getAvatarUrl());
                member.setGender(userInfo.getGender());
            }
            member.setSource("5");
            member.setStoreId(appletLoginRedisParamResponse.getStoreId());
            member.setMobile(RandomMathLetter.randomInt(11));
            member.setPassword("123456");
            member.setRelename("魔金" + RandomMathLetter.randomString(4));
            member.setAppletOpenId(weChatAppletLoginResponse.getOpenid());
            member.setConsumptionAmount(BigDecimal.ZERO);
            //设置自己的推荐码
            member.setRecommondCode(appletLoginRedisParamResponse.getRecommondCode());
            memberService.insertUmsMember(member);
            //向线程池提交任务
            UmsMember finalMember = member;
            ThreadTask.getInstance().addTask(() -> {
                registerServiceApi.registerCoupon(finalMember.getId());
            });
            res.put("member", member);
        }
        sb.append(Jwts.builder().setSubject(member.getUsername())
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(SignatureAlgorithm.HS256, jwtSecretKey)
                .setIssuedAt(new Date())
                .claim("userName", member.getUsername())
                .claim("nickName", member.getNickname())
                .claim("releName", member.getRelename())
                .claim("id", member.getId())
                .setExpiration(Date.from(Instant.now().plus(1, ChronoUnit.HOURS))) // 有效期1小时
                .compact());
        appletLoginRedisParamResponse.setToken(sb.toString());
        redisService.putToRedis(String.format(Rediskey.TOKEN, sb.toString()), JSON.toJSONString(member),100, TimeUnit.DAYS);
        res.put("sessionKey", weChatAppletLoginResponse.getSession_key());
        res.put("access_token", sb.toString());
        res.put("refresh_token", sb.toString());
        return AjaxResult.success(res);

    }
    @PostMapping("/wxapp/bindingPhone")
    @ApiOperation(value = "小程序绑定手机号", notes = "小程序绑定手机号")
    public AjaxResult phone(@Validated @RequestBody AppletLoginRedisParamResponse param, HttpServletRequest request) {

        Long uid = AppletsLoginUtils.getInstance().getCustomerId(request);
        UmsMember userQueryVo = memberService.queryCustomerInfoById(uid);
        if(userQueryVo==null){
            return AjaxResult.error("请先登录!");
        }
        if("1".equals(userQueryVo.getIsMobileVerification())){
            return AjaxResult.error("您的账号已经绑定过手机号码");
        }

        //解析手机号
        WxPhoneInfo wxPhoneInfo = null;

        try {
            String result = AES.wxDecrypt(param.getEncryptedData(), param.getSessionKey(), param.getIv());
            Gson gson = new Gson();
            wxPhoneInfo = gson.fromJson(result, WxPhoneInfo.class);
            if (wxPhoneInfo != null) {
                UmsMember newUserQueryVo = memberService.queryCustomerByName(wxPhoneInfo.getPhoneNumber(),param.getStoreId());
                if (newUserQueryVo!=null){
                    return AjaxResult.error("手机号码已被绑定");
                }
                userQueryVo.setMobile(wxPhoneInfo.getPhoneNumber());
                userQueryVo.setIsMobileVerification("1");
                memberService.updateUmsMember(userQueryVo);
                return AjaxResult.success(wxPhoneInfo.getPhoneNumber());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error("绑定失败");

    }

    @UnAuth
    @ResponseBody
    @RequestMapping("/appLogin")
    public Object appLogin(@RequestParam String openid,
                           @RequestParam Integer sex,
                           @RequestParam String headimgurl,
                           @RequestParam String unionid,
                           @RequestParam String nickname,
            @RequestParam(value = "recommondCode", required = false) String recommondCode,
                           @RequestParam String city,
                           @RequestParam(value = "storeId", required = false, defaultValue = "0") long storeId,
                           @RequestParam Integer source) {

        if (openid == null || "".equals(openid)) {
            return AjaxResult.error("openid为空");
        }
        try {

            final StringBuilder sb = new StringBuilder();

            Map<String, Object> res = new HashMap<>();

            UmsMember member = memberService.queryCustomerByappOpenId(openid,storeId);
            if (member != null) {
                res.put("member", member);
            } else {
                member = new UmsMember();
                member.setNickname(nickname);
                member.setImage(headimgurl);
                member.setGender(sex + "");
                member.setSource("2");
                member.setStoreId(storeId);
                member.setMobile(RandomMathLetter.randomInt(11));
                member.setPassword("123456");
                member.setRelename("魔金" + RandomMathLetter.randomString(4));
                member.setAppletOpenId(openid);
                member.setRecommondCode(recommondCode);

                memberService.insertUmsMember(member);
                //向线程池提交任务
                UmsMember finalMember = member;
                ThreadTask.getInstance().addTask(() -> {
                    registerServiceApi.registerCoupon(finalMember.getId());
                });
                res.put("member", member);
            }
            sb.append(Jwts.builder().setSubject(member.getUsername())
                    .compressWith(CompressionCodecs.DEFLATE)
                    .signWith(SignatureAlgorithm.HS256, jwtSecretKey)
                    .setIssuedAt(new Date())
                    .claim("userName", member.getUsername())
                    .claim("nickName", member.getNickname())
                    .claim("releName", member.getRelename())
                    .claim("id", member.getId())
                    .setExpiration(Date.from(Instant.now().plus(1, ChronoUnit.HOURS))) // 有效期1小时
                    .compact());
            redisService.putToRedis(String.format(Rediskey.TOKEN, sb.toString()), JSON.toJSONString(member),100, TimeUnit.DAYS);
            res.put("access_token", sb.toString());
            res.put("refresh_token", sb.toString());
            return AjaxResult.success(res);
        } catch (AuthenticationException e) {
            return AjaxResult.error("用户名或密码错误");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 绑定公众号
     */
    @GetMapping("/wechatlogin")
    @UnAuth
    @ApiIgnore
    public void wechatLogin(String code, String state, long storeId, HttpServletResponse response, HttpServletRequest request) throws Exception {
        log.debug("wechatLogin and code:{} \r\n state:{} \r\n ", code, state);
        WechatPaySet wechatAppletPaySet = paySetService.queryPaySet(storeId).getWechatPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
        wechatSetting.setUrl(wechatAppletPaySet.getLoginNotice());

        //获取accesstoken
        AccessTokenResult weChatAppletLoginResponse = WechatUtils.getAccessToken(code, state, wechatSetting);
        if (ObjectUtils.isEmpty(weChatAppletLoginResponse) || weChatAppletLoginResponse.isError()) {
            log.error("wechatLogin error : getAccessToken fail");
        }
        UmsMember member = memberService.queryCustomerByh5OpenId(weChatAppletLoginResponse.getOpenid(),storeId);
        if (member != null) {

        } else {
            member = memberService.queryCustomerWithNoPasswordById(AppletsLoginUtils.getInstance().getCustomerId(request));
            if (member != null) {
                member.setH5OpenId(weChatAppletLoginResponse.getOpenid());
                memberService.updateUmsMember(member);
            }
        }
        response.sendRedirect(state);
    }

    /**
     * 小程序获取openid 并更新当前用户，也就是手机登录后小程序授权
     *
     * @param 。开发者需要在开发者服务器后台调用 api，使用 code 换取 openid 和 session_key 等信息
     * @return 登录信息
     */
    @UnAuth
    @ResponseBody
    @RequestMapping("/getOpenId")
    @ApiOperation(value = "小程序获取登录信息", notes = "小程序获取登录信息（不需要认证）", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "code", value = "用户登录凭证"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "登录信息", response = AppletLoginInfo.class)
    })
    public AjaxResult getOpenId(@RequestBody AppletLoginRedisParamResponse appletLoginRedisParamResponse, HttpServletRequest request) {

        WechatPaySet wechatAppletPaySet = paySetService.queryPaySet(appletLoginRedisParamResponse.getStoreId()).getWechatAppletPaySet();
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId(wechatAppletPaySet.getAppId());
        wechatSetting.setAppSecret(wechatAppletPaySet.getAppSecret());
        if (!wechatSetting.checkAppletOAuthParams()) {
            log.error("getLoginInfo fail:checkAppletOAuthParams fail");
            return AjaxResult.error("getLoginInfo fail:checkAppletOAuthParams fail");
        }
        WeChatAppletLoginResponse weChatAppletLoginResponse = WeChatAppletUtils.getLoginInfo(appletLoginRedisParamResponse.getCode(), wechatSetting);
        if (Objects.isNull(weChatAppletLoginResponse)) {
            log.error("getLoginInfo fail: getLoginInfo fail");
            return AjaxResult.error("getLoginInfo fail: getLoginInfo fail");
        }
        UmsMember member = new UmsMember();
        log.info("getOpenId : openid==" + weChatAppletLoginResponse.getOpenid());
        member.setAppletOpenId(weChatAppletLoginResponse.getOpenid());
        long customerId = AppletsLoginUtils.getInstance().getCustomerId(request);
        member.setId(customerId);
        return AjaxResult.success(memberService.updateUmsMember(member));
    }
    /**
     * 获取token
     *
     * @param request request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        // 认证信息在header 中的key
        final String authHeader = request.getHeader("Authorization");

        if (Objects.isNull(authHeader) || !authHeader.startsWith("Bearer")) {
            log.info("getClaims fail :Authorization fail ");
            throw new UnAuthorizedException(ResultCode.WX_NOT_AUTHORIZED);
        }
        return authHeader.length() >= 7 ? authHeader.substring(7) : authHeader.substring(6);
    }


}
